package edu.zut.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "ShowTimeServlet2", value = "/showTime2")
public class ShowTimeServlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //先尝试获取cookie中的上次访问时间
        //从请求中获取当前所有cookie对象
        Cookie[] cookies = request.getCookies();
        System.out.println(cookies.length + "---------");
        //flag 将其视为是否存在上次访问时间cookie的依据
        boolean flag = true;
        if (cookies != null && cookies.length != 0) {
            //遍历cookies
            for (Cookie cookie : cookies) {
                //如果保存的有上次访问时间
                if (cookie.getName().equals("lastTime")) {
                    String value = cookie.getValue();
                    value = URLDecoder.decode(value, "utf-8");
                    //重新将当前访问时间保存进去
                    Date date = new Date();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
                    String now = dateFormat.format(date);
                    now = URLEncoder.encode(now, "utf-8");
                    cookie.setValue(now);
                    //重新将其返回给浏览器
                    response.addCookie(cookie);
                    response.getWriter().write("上次访问时间：" + value);
                    flag = false;
                    break;
                }
            }
        }
        if (cookies == null || cookies.length == 0 || flag) {
            //新建cookie将当前时间保存进去
            //重新将当前访问时间保存进去
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
            String now = dateFormat.format(date);
            response.getWriter().write("这是第一次访问：" + now);
            now = URLEncoder.encode(now, "utf-8");
            Cookie cookie = new Cookie("lastTime", now);
            response.addCookie(cookie);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
